package yf.mall.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.yf.response.RRException;
import com.yf.service.SmsService;
import com.yf.service.WxNoticeService;
import com.yf.utils.DateUtil;
import com.yf.utils.KaptchaUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import yf.mall.dao.KolOrderDao;
import yf.mall.dao.MallGoodsDao;
import yf.mall.dao.UserDao;
import yf.mall.entity.UserEntity;
import yf.mall.enums.QuestionStatusEnum;
import yf.mall.service.NoticeService;
import yf.mall.sms.ChuangLanSms;
import yf.mall.utils.EmojiFilter;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@EnableAsync
public class MyNoticeServiceImpl implements NoticeService {

    @Autowired
    private WxNoticeService noticeService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private MallGoodsDao mallGoodsDao;

    //阿里短信模板
    @Value("${SMS.ALI.CAPTCHA_TEM}")
    private String captcha_tem;

    //微信资金变动模板
    @Value("${SMS.WX.ACCOUNT_TEM}")
    private String account_tem;

    //微信产品入库模板
    @Value("${SMS.WX.ORDER_IN_TEM}")
    private String order_in_tem;

    //微信产品出库模板
    @Value("${SMS.WX.ORDER_OUT_TEM}")
    private String order_out_tem;

    //微信下单成功模板
    @Value("${SMS.WX.ORDER_DONE_TEM}")
    private String order_done_tem;

    //微信发货物流通知
    @Value("${SMS.WX.ORDER_LOG_TEM}")
    private String order_log_tem;

    //微信用户注册通知
    @Value("${SMS.WX.USER_IN_TEM}")
    private String user_in_tem;

    @Value("${SMS.WX.WELFARE_TEM}")
    private String welfare_tem;
    @Value("${SMS.WX.QUESTION_TEM}")
    private String question_tem;
    @Value("${SMS.WX.QUESTION_EXA_TEM}")
    private String question_exa_tem;
    //提现申请通知
    @Value("${SMS.WX.APPLY_CASH}")
    private String apply_cash;
    //提现申请结果通知
    @Value("${SMS.WX.APPLY_CASH_STATUS}")
    private String apply_cash_status;
    //app地址前缀
    @Value("${APP.BASE_URL}")
    private String app_base_url;
    //账户明细地址
    @Value("${APP.ACCOUNT_URL}")
    private String app_account_url;
    //订单地址
    @Value("${APP.ORDER_URL}")
    private String app_order_url;
    //用户地址
    @Value("${APP.USER_URL}")
    private String app_user_url;
    @Value("${APP.QUESTION_URL}")
    private String question_url;

    @Override
    @Async
    public void sendConfirmCourse(String openId, String courserName, String courseInfo) {
        try {
            //发送激活通知
            String tempId = "33qqKCp8Fc30vcLELtLl7r0rNoZ1zQo0cSrIxpVPIOk";
            String url = "http://app.zmzpl.com/zbmall/confirm";
            Map<String, String> data = new HashMap<>();
            data.put("first", "您的报名已经通过审核,请尽快确认参加,否则将不会生效!");
            data.put("keyword1", courserName);
            data.put("keyword2", "等待确认");
            data.put("remark", courseInfo);
            noticeService.send(openId, tempId, url, data);
        } catch (Exception e) {
            log.error("发送激活通知失败" + e.getMessage());
        }
    }

//    @Override
//    public String sendCaptcha(String mobile) {
//        String text = KaptchaUtil.createProducer().createText();
//        try {
//            String tempId = captcha_tem;
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("code", text);
//            smsService.send(mobile, tempId, jsonObject.toString());
//        } catch (Exception e) {
//
////            e.printStackTrace();
//            log.error("发送验证码消息失败" + e.getMessage());
//            throw new RRException(e.getMessage());
//        }
//
//        return text;
//    }


    @Override
    public String sendCaptcha(String mobile) {
        String text = KaptchaUtil.createProducer().createText();
        ChuangLanSms.sendCaptcha(mobile, text);
        return text;
    }

    @Override
    public void sendCourseToAdmin(String phone, String name, Integer number) {
        try {
            String tempId = "SMS_176527431";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", name);
            jsonObject.put("number", number);
            smsService.send(phone, tempId, jsonObject.toString());
        } catch (Exception e) {
//           e.printStackTrace();
            log.error("预报名已满发送开课通知给管理员失败" + e.getMessage());
        }
    }

    @Override
    public void sendGoodsDown(String mobile, String name) {
        try {
            String tempId = "SMS_199796856";
            JSONObject jsonObject = new JSONObject();
            smsService.send(mobile, tempId, jsonObject.toString());
        } catch (Exception e) {
//           e.printStackTrace();
            log.error("上架通知失败" + e.getMessage());
        }
    }

    @Override
    public void sendShopNoPass(String phone, String name, String info) {
        try {
            String tempId = "SMS_200721276";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", name);
            jsonObject.put("info", info);
            jsonObject.put("phone", "19976682053");
            smsService.send(phone, tempId, jsonObject.toString());
        } catch (Exception e) {
//           e.printStackTrace();
            log.error("店铺审核不通过通知失败" + e.getMessage());
        }
    }

    @Override
    public void sendShopPass(String phone, String name, String shop) {
        try {
            String tempId = "SMS_199796845";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", name);
            jsonObject.put("shop", shop);
            smsService.send(phone, tempId, jsonObject.toString());
        } catch (Exception e) {
//           e.printStackTrace();
            log.error("店铺审核通过失败" + e.getMessage());
        }
    }

    //    开店申请通知
    @Override
    public void sendOpenShop(String phone, String name) {
        try {
            String tempId = "SMS_199791918";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", name);
            smsService.send(phone, tempId, jsonObject.toString());
        } catch (Exception e) {
//           e.printStackTrace();
            log.error("开店申请通知失败" + e.getMessage());
        }
    }

    /**
     * 提现通知
     *
     * @param openId
     * @param amount
     * @param time
     * @param type
     * @param info
     */
    @Override
    @Async
    public void sendApplyCash(String openId, String amount, Date time, String type, String info) {
        if (openId == null) return;
        try {
            //发送激活通知
            String tempId = apply_cash;
            String url = app_base_url + app_account_url;
            Map<String, String> data = new HashMap<>();
            data.put("first", info);

            if (amount != null) {
                data.put("keyword1", amount);
            }
            if (time != null) {
                data.put("keyword2", time.toString());
            }
            data.put("remark", "点击前往平台查看明细!");
            noticeService.send(openId, tempId, url, data);
        } catch (Exception e) {
            log.error("发送提现申请通知失败" + e.getMessage());
        }
    }

    @Override
    @Async
    public void sendApplyCashStatus(String openId, String amount, Date crateTime, Date passTime, String type, String status, String info) {
        if (openId == null) return;
        try {
            //发送激活通知
            String tempId = apply_cash_status;
            String url = app_base_url + app_account_url;
            Map<String, String> data = new HashMap<>();
            data.put("first", info);
            if (crateTime != null) {
                data.put("keyword3", crateTime.toString());
            }
            if (amount != null) {
                data.put("keyword1", amount);
            }
            data.put("keyword2", type);
            data.put("keyword4", status);
            data.put("keyword5", passTime.toString());
            data.put("remark", "前往平台查看明细!");
            noticeService.send(openId, tempId, url, data);
        } catch (Exception e) {
            log.error("发送提现申请通知失败" + e.getMessage());
        }
    }

    @Override
    @Async
    public void sendAccount(String openId, String amount, BigDecimal nowAmount, String type, String info) {
        if (openId == null) return;
        log.info("发送账户通知中...");
        try {
            //发送激活通知
            if (nowAmount != null) {
                nowAmount = nowAmount.setScale(2, BigDecimal.ROUND_DOWN);
            }
            String tempId = account_tem;
            String url = app_base_url + app_account_url;
            Map<String, String> data = new HashMap<>();
            data.put("first", info);
            data.put("keyword1", DateUtil.dateToStr(new Date()));
            data.put("keyword2", type);
            if (amount != null) {
                data.put("keyword3", amount);
            }
            if (nowAmount != null) {
                data.put("keyword4", String.valueOf(nowAmount));
            }
            data.put("remark", "点击前往平台查看明细!");
//            noticeService.send(openId, tempId, url, data);
        } catch (Exception e) {
            log.error("发送账户通知失败" + e.getMessage());
        }
    }


    @Override
    @Async
    public void sendDyOrder(String openId, String name, String orderId, Integer amount, String goodsName, Date date) {
        log.info("发送抖音订单通知....{},{},{},{}", openId, orderId, amount, name);
        try {
            Map<String, String> data = new HashMap<>();
            data.put("character_string3", orderId);
            if (goodsName != null && goodsName.length() > 20) {
                goodsName = goodsName.substring(0, 19);
            }
            data.put("thing9", goodsName);
//            name = EmojiFilter.filterAll(name);
//            if(name.length()>5){ //phrase 最多五个字符
//                name = name.substring(0,5);
//            }
            data.put("phrase7", "抖音订单");
            data.put("amount4", new BigDecimal(amount).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN).doubleValue() + "");
            data.put("time8", DateUtil.dateToStr(date));
            String appId = wxMaService.getWxMaConfig().getAppid();
            String path = "pages/main/main";
            noticeService.send(openId, "1fYDz8TnaJTPm97yK7KWZqwQJnTsZ-5dRgRZbWY2cZI", appId, path, data);
            log.info("发送抖音订单通知完成....{},{},{},{}", openId, orderId, amount, name);
        } catch (Exception e) {
            log.error("发送抖音订单通知失败,{}", orderId);
            e.printStackTrace();
        }

    }


    @Override
    public void sendDyExpOrder(String openId, String name, String goodsName, Integer amount, Date date) {
        log.info("发送抖音订单爆单通知....{},{},{}", openId, name, amount);
        try {
            Map<String, String> data = new HashMap<>();
            data.put("thing9", "爆单提醒,一分钟超过" + amount + "单!");
            if (goodsName != null && goodsName.length() > 20) {
                goodsName = goodsName.substring(0, 19);
            }
            data.put("thing14", goodsName);
            //去除表情
            name = EmojiFilter.filterAll(name);
            data.put("thing10", name);
//            data.put("amount4", new BigDecimal(amount).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN).doubleValue() + "");
            data.put("time12", DateUtil.dateToStr(date));
            String appId = wxMaService.getWxMaConfig().getAppid();
            String path = "pages/main/main";
            noticeService.send(openId, "Cj0cUxG35O7jYkrPH89NJUXFyRrEC7K_-kf0DpvLDCA", appId, path, data);
        } catch (Exception e) {
            log.error("发送抖音订单爆单通知失败{}", name);
            e.printStackTrace();
        }
    }

    @Override
    @Async
    public void sendDyTemp(List<String> openIds, String info) {
        log.info("发送抖音订单模版通知,数量:{}", openIds.size());
        Map<String, String> data = new HashMap<>();
        data.put("time12", DateUtil.dateToStr(new Date()));
        data.put("thing9", info);
        try {
            for (String openId : openIds) {
                String appId = wxMaService.getWxMaConfig().getAppid();
                String path = "pages/main/main";
                noticeService.send(openId, "Cj0cUxG35O7jYkrPH89NJT5DDj4GoX6XDOzH6IjK9dw", appId, path, data);
            }
        } catch (Exception e) {
            log.error("发送订单通知失败");
            e.printStackTrace();
        }

    }

    @Resource
    private WxMaService wxMaService;


    @Override
    @Async
    public void sendAccountByUserId(Long userId, String amount, BigDecimal nowAmount, String type, String info) {
        UserEntity user = userDao.get(userId);
        if (user == null || user.getOpenId() == null) {
            return;
        }
        String openId = user.getOpenId();
        try {
            //发送激活通知
            if (nowAmount != null) {
                nowAmount = nowAmount.setScale(2, BigDecimal.ROUND_DOWN);
            }
            String tempId = account_tem;
            String url = app_base_url + app_account_url;
            Map<String, String> data = new HashMap<>();
            data.put("first", info);
            data.put("keyword1", type);
            if (amount != null) {
                data.put("keyword2", amount);
            }
            data.put("keyword3", DateUtil.dateToStr(new Date()));
            if (nowAmount != null) {
                data.put("keyword4", String.valueOf(nowAmount));
            }
            data.put("remark", "点击前往平台查看明细!");
            noticeService.send(openId, tempId, url, data);
        } catch (Exception e) {
            log.error("发送账户通知失败" + e.getMessage());
        }
    }

    @Override
    @Async
    public void sendOrderIn(String openId, String name, String detail) {
        if (openId == null) return;
        try {
            //发送激活通知
            String tempId = order_in_tem;
            String url = app_base_url + app_order_url;
            Map<String, String> data = new HashMap<>();
            data.put("first", name + "有一批产品入库");
            data.put("keyword1", detail);
            data.put("keyword2", DateUtil.dateToStr(new Date()));
            data.put("remark", "点击前往平台查看明细!");
            noticeService.send(openId, tempId, url, data);
        } catch (Exception e) {
            log.error("发送入库通知失败" + e.getMessage());
        }
    }

    @Override
    public void sendOrderOut(String openId, String orderNo, String detail) {
        try {
            //发送激活通知
            String tempId = order_out_tem;
            String url = app_base_url + app_order_url;
            Map<String, String> data = new HashMap<>();
            data.put("first", "您有一批产品出库");
            data.put("keyword1", orderNo);
            data.put("keyword2", detail);
            data.put("remark", "点击前往平台查看明细!");
            noticeService.send(openId, tempId, url, data);
        } catch (Exception e) {
            log.error("发送出库通知失败" + e.getMessage());
        }
    }

    @Override
    public void sendNewOrder(String openId, String orderNo, String detail) {
        try {
            //发送激活通知
            String tempId = order_out_tem;
            String url = app_base_url + app_order_url;
            Map<String, String> data = new HashMap<>();
            data.put("first", "您的店铺有新的订单，请注意查看！");
            data.put("keyword1", orderNo);
            data.put("keyword2", detail);
            data.put("remark", "点击前往平台查看明细!");
            noticeService.send(openId, tempId, url, data);
        } catch (Exception e) {
            log.error("发送出库通知失败" + e.getMessage());
        }
    }

    @Override
    @Async
    public void sendUserIn(String openId, String userName, String mobile) {
        if (openId == null) return;
        try {
            //发送激活通知
            String tempId = user_in_tem;
            String url = app_base_url + app_user_url;
            Map<String, String> data = new HashMap<>();
            data.put("first", "有新用户注册");
            data.put("keyword1", userName);
            data.put("keyword2", mobile);
            data.put("keyword3", DateUtil.dateToStr(new Date()));
            data.put("remark", "点击前往平台查看明细!");
            noticeService.send(openId, tempId, url, data);
            log.info("发送成功" + openId);
        } catch (Exception e) {
            log.error("发送注册通知失败" + e.getMessage());
        }
    }

    @Override
    @Async
    public void sendOrderDone(String openId, String name, String detail, String payWay, BigDecimal amount) {
        if (openId == null) return;
        try {
            String tempId = order_done_tem;
            String url = app_base_url + app_order_url;
            log.info(url);
            Map<String, String> data = new HashMap<>();
            data.put("first", name + "下单成功!");
            data.put("keyword1", detail);
            data.put("keyword2", "");
            data.put("keyword3", String.valueOf(amount));
            data.put("remark", "点击前往平台查看明细!");
            noticeService.send(openId, tempId, url, data);
        } catch (Exception e) {
            log.error("发送下单通知失败" + e.getMessage());
        }
    }

    @Override
    @Async
    public void sendOrderLog(String openId, String orderNo, String name, String company, String logNo, String address) {

        try {
            if (openId == null) return;
            String tempId = order_log_tem;
            if (tempId == null) return;
            String url = app_base_url + app_order_url;
            Map<String, String> data = new HashMap<>();
            data.put("first", name + "您的订单已经发货!");
            data.put("keyword1", orderNo);
            data.put("keyword2", DateUtil.dateToStr(new Date()));
            data.put("keyword3", company);
            data.put("keyword4", logNo);
            data.put("keyword5", address);
            data.put("remark", "点击前往平台查看明细!");
            noticeService.send(openId, tempId, url, data);
        } catch (Exception e) {
            log.error("发送发货通知失败" + e.getMessage());
        }
    }

    @Override
    public void noticeWelFare(String openId, String name, BigDecimal amount) {
        try {
            amount = amount.setScale(2, BigDecimal.ROUND_DOWN);
            if (openId == null) return;
            String tempId = welfare_tem;
            if (tempId == null) return;
            String url = app_base_url + app_order_url;
            Map<String, String> data = new HashMap<>();
            data.put("first", "和之有情，爱之有行");
            data.put("keyword1", "关心下一代成长");
            data.put("keyword2", DateUtil.dateToStr(new Date()));
            data.put("keyword3", amount + "元");
            data.put("remark", "感谢您为爱媂缇丽关心一下代成长基金奉献爱心!");
            noticeService.send(openId, tempId, url, data);
        } catch (Exception e) {
            log.error("发送发货通知失败" + e.getMessage());
        }
    }

    @Override
    public void noticeQuestion(String openId, String question) {
        try {
            if (openId == null) return;
            String tempId = question_tem;
            if (tempId == null) return;
            String url = app_base_url + question_url;
            Map<String, String> data = new HashMap<>();
            data.put("first", "您的店铺有最新提问,请及时查看和回复");
            data.put("keyword1", question);
            data.put("keyword2", QuestionStatusEnum.AUDIT.getValue());
            data.put("keyword3", null);
            data.put("remark", "你可以点击详情进入商城进行回答,或前往店铺后台进行审核通过回答");
            noticeService.send(openId, tempId, url, data);
        } catch (Exception e) {
            log.error("发送问题通知失败" + e.getMessage());
        }
    }

    @Override
    public void noticeQuestionExa(String openId, String cause, String time, String question) {
        try {
            if (openId == null) return;
            String tempId = question_exa_tem;
            if (tempId == null) return;
            String url = app_base_url + question_url;
            Map<String, String> data = new HashMap<>();
            data.put("first", "抱歉，您的提问没有通过审核。");
            data.put("keyword1", cause);
            data.put("keyword2", time);
            data.put("keyword3", "建议您重新向店铺发起提问");
            data.put("remark", question);
            noticeService.send(openId, tempId, url, data);
        } catch (Exception e) {
            log.error("发送问题审核通知失败" + e.getMessage());
        }
    }

    @Override
    public void noticeAnswerExa(String openId, String cause, String time, String answer) {
        try {
            if (openId == null) return;
            String tempId = question_exa_tem;
            if (tempId == null) return;
            String url = app_base_url + question_url;
            Map<String, String> data = new HashMap<>();
            data.put("first", "抱歉，您的回答没有通过审核。");
            data.put("keyword1", cause);
            data.put("keyword2", time);
            data.put("keyword3", "建议您重新回到店铺后台修改回答");
            data.put("remark", answer);
            noticeService.send(openId, tempId, url, data);
        } catch (Exception e) {
            log.error("发送回答审核通知失败" + e.getMessage());
        }
    }
}
